Vue check if item already exists in array or Object:To check if an item already exists in an array using Vue.js, you can use the includes method. This method checks whether an element is present in an array or not and returns a boolean value indicating its presence.
How can I check if an item already exists in an array in Vue js?
In the code snippet, you are already using the includes() method to check if an item exists in the myArray array. This method returns true if the item exists, and false otherwise.
The computed property itemExists uses this method to check if myItem exists in myArray. If it does, it returns true and the first <p> element with the v-if directive is displayed. If it doesn’t, it returns false and the second <p> element with the v-else directive is displayed.
So, the way you are checking if an item already exists in an array in Vue js is correct. You can use the includes() method to check if an item exists in an array, and you can use a computed property to return the result and conditionally display content based on that result.
Vue check if item already exists in array Example
<div id="app">
<p v-if="itemExists">Item already exists in the array</p>
<p v-else>Item does not exist in the array</p>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
myArray: ['apple', 'banana', 'orange'],
myItem: 'banana'
}
},
computed: {
itemExists() {
return this.myArray.includes(this.myItem)
}
}
});
</script>
Output of Vue Js Check If Item Already Exists In Array



